package kevin.workplan.web.filter;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kevin.lib.util.JsonUtil;
import kevin.workplan.util.Constant;
import kevin.workplan.util.SessionUtil;
import kevin.workplan.util.Util;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 对admin登陆栏截
 * 
 * @author huangjinjie
 * 
 */
public class SessionFilter implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object o) throws Exception {
		// 后台session控制
		String uri = request.getServletPath();
		if (uri.startsWith("/login"))
			return true;

		if (!SessionUtil.isLogin(request.getSession())) {
			if(uri.endsWith(".json")) {
				// json生成json返回
				Map<String, Object> json = new HashMap<String, Object>();
				json.put("code", Constant.JSON_UNLOGIN);
				response.getWriter().write(JsonUtil.toJson(json));
			} else {
				String refUrl = request.getRequestURL().toString();
				if (!Util.empty(request.getQueryString()))
					refUrl += "?" + request.getQueryString();
				refUrl = URLEncoder.encode(refUrl);
				response.sendRedirect(request.getContextPath()
						+ "/admin/login?refUrl=" + refUrl);
			}
			return false;
		} else {
			return true;
		}
	}

	@Override
	public void postHandle(HttpServletRequest httpServletRequest,
			HttpServletResponse response, Object o, ModelAndView modelAndView)
			throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest httpServletRequest,
			HttpServletResponse response, Object o, Exception e)
			throws Exception {

	}
}